<template>
  <div>
    <!-- 按钮组 -->
    <el-button type="primary" @click="showSearchByIdDialog">根据ID查询拍卖活动</el-button>
    <el-button type="primary" @click="showSearchByConditionsDialog">条件搜索拍卖活动</el-button>
    <el-button type="primary" @click="handleReset">重置所有搜索</el-button>
    <el-button type="primary" @click="showOngoingAuctions">进行中的拍卖</el-button>
    <el-button type="primary" @click="showUpcomingAuctions">未开始的拍卖</el-button>

    <!-- 表格展示拍卖活动 -->
    <el-table :data="auctionList" stripe border>
      <el-table-column label="拍卖ID" prop="id"></el-table-column>
      <el-table-column label="车辆ID" prop="carId"></el-table-column>
      <el-table-column label="开始时间" prop="startTime"></el-table-column>
      <el-table-column label="结束时间" prop="endTime"></el-table-column>
      <el-table-column label="起拍价格" prop="startingPrice"></el-table-column>
      <el-table-column label="加价幅度" prop="increaseAmount"></el-table-column>
      <el-table-column label="当前价格" prop="currentPrice"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="showCarInfo(scope.row.carId)">查看车辆信息</el-button>
          <!-- 如果系统时间早于开始时间，则显示 "预约" 按钮 -->
          <el-button v-if="compareTime(scope.row.startTime, 'before')" type="text"
                     @click="handleAppointment(scope.row.id)">预约
          </el-button>
          <!-- 如果系统时间晚于开始时间，则显示 "出价" 按钮 -->
          <el-button v-if="compareTime(scope.row.startTime, 'after')" type="text"
                     @click="showBidDialog(scope.row.id, scope.row.carId)">出价
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    >
    </el-pagination>

    <!-- 根据ID查询对话框 -->
    <el-dialog title="根据ID查询拍卖活动" :visible.sync="searchByIdDialogVisible" width="30%">
      <el-form :model="searchByIdForm" inline>
        <el-form-item label="拍卖ID">
          <el-input v-model="searchByIdForm.id" placeholder="请输入拍卖ID"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getAuctionById">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 条件搜索对话框 -->
    <el-dialog title="条件搜索拍卖活动" :visible.sync="searchByConditionsDialogVisible" width="50%">
      <el-form :model="searchByConditionsForm" inline>
        <el-form-item label="开始时间">
          <el-input v-model="searchByConditionsForm.startTime" placeholder="请输入开始时间"></el-input>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-input v-model="searchByConditionsForm.endTime" placeholder="请输入结束时间"></el-input>
        </el-form-item>
        <el-form-item label="起拍价格">
          <el-input v-model.number="searchByConditionsForm.startingPrice" placeholder="请输入起拍价格"></el-input>
        </el-form-item>
        <el-form-item label="加价幅度">
          <el-input v-model.number="searchByConditionsForm.increaseAmount" placeholder="请输入加价幅度"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchAuctionByConditions">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 出价对话框 -->
    <el-dialog title="出价" :visible.sync="bidDialogVisible" width="30%">
      <el-form :model="bidForm" inline>
        <el-form-item>
          <el-input v-model="bidForm.price" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleBid(bidForm.price)">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 汽车信息弹窗 -->
    <el-dialog title="车辆信息" :visible.sync="carInfoDialogVisible" width="50%">
      <el-table :data="carInfoList" stripe border>
        <el-table-column label="车辆图片" width="120">
          <template slot-scope="scope">
            <!-- 检查图片数组是否存在，且不为空 -->
            <img v-if="scope.row.imgs && scope.row.imgs.length > 0" :src="scope.row.imgs[0].imageUrl" class="avatar">
          </template>
        </el-table-column>
        <el-table-column label="车辆编号" prop="id"></el-table-column>
        <el-table-column label="品牌" prop="brand"></el-table-column>
        <el-table-column label="型号" prop="model"></el-table-column>
        <el-table-column label="年份" prop="year"></el-table-column>
        <el-table-column label="里程数" prop="mileage"></el-table-column>
        <el-table-column label="颜色" prop="color"></el-table-column>
        <el-table-column label="车辆状况描述" prop="conditionDescription"></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 确认预约对话框 -->
    <el-dialog title="确认预约" :visible.sync="confirmAppointmentDialogVisible" width="30%">
      <p>是否预约该活动？</p>
      <span slot="footer" class="dialog-footer">
          <el-button @click="confirmAppointmentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAppointment">确定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import {Message, Loading} from 'element-ui';

export default {
  data() {
    return {
      searchByIdDialogVisible: false,
      searchByConditionsDialogVisible: false,
      bidDialogVisible: false,
      confirmAppointmentDialogVisible: false,
      searchByIdForm: {id: ''},
      searchByConditionsForm: {
        startTime: '',
        endTime: '',
        startingPrice: null,
        increaseAmount: null,
      },
      bidForm: {price: null},
      auctionList: [],
      carInfoList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loadingInstance: null,
      carInfoDialogVisible: false,
      currentActivityId: null,
      currentCarId: null,
      bidCounts: {}, // 存储每个订单的出价次数
      myBidPrices: {}, // 存储每个订单的出价价格
      maxBidCount: 3, // 最大出价次数限制
    };
  },
  created() {
    this.loadAuctionData();
  },
  methods: {
    // 比较系统时间和拍卖活动开始时间
    compareTime(startTime, condition) {
      const currentTime = new Date();
      const auctionStartTime = new Date(startTime);
      if (condition === 'before') {
        return currentTime < auctionStartTime;
      } else if (condition === 'after') {
        return currentTime > auctionStartTime;
      }
      return false;
    },
    // 点击按钮查看进行中的拍卖活动
    showOngoingAuctions() {
      this.auctionList = this.auctionList.filter(auction => {
        return this.compareTime(auction.startTime, 'after');
      });
    },
    // 点击按钮查看未开始的拍卖活动
    showUpcomingAuctions() {
      this.auctionList = this.auctionList.filter(auction => {
        return this.compareTime(auction.startTime, 'before');
      });
    },
    async loadAuctionData() {
      this.loadingInstance = Loading.service({fullscreen: true});
      try {
        const response = await axios.get(`/api/auction/list/${this.currentPage}/${this.pageSize}`);
        if (response.data.code === 200) {
          const auctionList = response.data.data.list;
          await this.updateCurrentPrices(auctionList); // 添加此行代码
          this.auctionList = auctionList.map(item => {
            return {...item, myBidPrice: this.myBidPrices[item.id] || null};
          });
          this.total = response.data.data.total;
        } else {
          Message.error('获取拍卖活动失败');
        }
      } catch (error) {
        Message.error('请求失败，请稍后重试');
      } finally {
        if (this.loadingInstance) {
          this.loadingInstance.close();
        }
      }
    },

     // 新增的方法用于更新拍卖活动列表中的当前价格
    async updateCurrentPrices(auctionList) {
      for (let item of auctionList) {
        const response = await axios.get('/api/user/activity/getLatestPrice', {
          params: {
            carId: item.carId
          }
        });
        if (response.data.code === 200) {
          item.currentPrice = response.data.data || null;
          item.bidPrice = response.data.data || null; // 可能也更新了出价价格
        } else {
          item.currentPrice = null;
        }
      }
    },

    async showCarInfo(carId) {
      try {
        const response = await axios.get(`/api/car/getById?carId=${carId}`);
        if (response.data.code === 200) {
          this.carInfoList = response.data.data.list;
          this.carInfoDialogVisible = true;
        } else {
          Message.error('获取车辆信息失败');
        }
      } catch (error) {
        Message.error('请求失败，请稍后重试');
      }
    },
    async getAuctionById() {
      const id = this.searchByIdForm.id;
      if (!id) {
        Message.warning('请输入拍卖ID');
        return;
      }
      try {
        const response = await axios.get(`/api/auction/getById?id=${id}`);
        if (response.data.code === 200) {
          this.auctionList = [response.data.data];
          this.total = 1;
          this.searchByIdDialogVisible = false;
        } else {
          Message.error('获取拍卖活动失败');
        }
      } catch (error) {
        Message.error('请求失败，请稍后重试');
      }
    },
    async searchAuctionByConditions() {
      const params = {
        startTime: this.searchByConditionsForm.startTime,
        endTime: this.searchByConditionsForm.endTime,
        startingPrice: this.searchByConditionsForm.startingPrice,
        increaseAmount: this.searchByConditionsForm.increaseAmount,
      };
      try {
        const response = await axios.get(`/api/auction/normal/list`, {params});
        if (response.data.code === 200) {
          const auctionList = response.data.data.list;
          this.auctionList = auctionList.map(item => {
            return {...item, myBidPrice: this.myBidPrices[item.id] || null};
          });
          this.total = response.data.data.total;
          this.searchByConditionsDialogVisible = false;
        } else {
          Message.error('获取拍卖活动失败');
        }
      } catch (error) {
        Message.error('请求失败，请稍后重试');
      }
    },
    showSearchByIdDialog() {
      this.searchByIdDialogVisible = true;
    },
    showSearchByConditionsDialog() {
      this.searchByConditionsDialogVisible = true;
    },
    showBidDialog(activityId, carId) {
      this.currentActivityId = activityId;
      this.currentCarId = carId;
      this.bidDialogVisible = true;
    },
    async handleBid(price) {
      try {
        const response = await axios.post(`/api/user/activity/bid`, {
          actId: this.currentActivityId,
          carId: this.currentCarId,
          price: price,
        });
        if (response.status === 200) {
          if (response.data.code === 200) {
            // 更新 myBidPrices 中当前拍卖活动的我的出价
            this.$set(this.myBidPrices, this.currentActivityId, price);

            // 更新当前拍卖活动的我的出价
            this.currentBidPrice = price;

            // 更新 auctionList 中的出价价格和当前价格
            const auctionIndex = this.auctionList.findIndex(
                (auction) => auction.id === this.currentActivityId
            );
            if (auctionIndex !== -1) {
              this.$set(this.auctionList, auctionIndex, {
                ...this.auctionList[auctionIndex],
                bidPrice: price,
                currentPrice: price,
              });
            }
            Message.success('出价成功');
            this.bidDialogVisible = false;
          } else if (response.data.code === 5003) {
            Message.error(`出价不符合最低出价要求（当前价格 + 出价幅度）`);
          } else if (response.data.code === 500) {
            Message.error('出价次数超过限制！最多出价三次！');
          }
        } else {
          Message.error('请求失败，请稍后重试');
        }
      } catch (error) {
        console.error(error);
        Message.error('请求失败，请稍后重试');
      }
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.loadAuctionData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadAuctionData();
    },
    handleReset() {
      this.searchByIdForm.id = '';
      this.searchByConditionsForm.startTime = '';
      this.searchByConditionsForm.endTime = '';
      this.searchByConditionsForm.startingPrice = null;
      this.searchByConditionsForm.increaseAmount = null;
      this.loadAuctionData();
    },
    // 点击预约按钮
    async handleAppointment(activityId) {
      this.currentActivityId = activityId;
      this.confirmAppointmentDialogVisible = true;
    },
    // 确认预约
    async confirmAppointment() {
      try {
        const response = await axios.get(`/api/user/activity/scheduled?actId=${this.currentActivityId}`);
        if (response.data.code === 200) {
          Message.success('预约成功');
          // 可选：在预约成功时更新界面或执行其他操作
          this.confirmAppointmentDialogVisible = false;
        } else {
          Message.error('预约失败');
        }
      } catch (error) {
        Message.error('请求失败，请稍后重试');
      }
    }
  },
  mounted() {

  },
};
</script>

<style scoped>
.avatar {
  width: auto;
  height: 80px;
}
</style>
